//
//  UserRegisterViewController.m
//  PalmChangtu
//
//  Created by osoons on 15/6/23.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "UserRegisterViewController.h"
#import "MainTabbarController.h"
#import "ProtocoliewWebController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
#import "ShareUserModel.h"

@interface UserRegisterViewController ()
{
    NSInteger countdownTiem60;

}
@end

@implementation UserRegisterViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    countdownTiem60 = 60;

    [_v_Top.lalTitel setText:@"注册"];
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
    [_v_Top.btnGoback removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_v_Top.btnGoback addTarget:self action:@selector(btnBack:) forControlEvents:UIControlEventTouchUpInside];

    [_btnRegister removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnRegister addTarget:self action:@selector(btnImmediatelyRegister:) forControlEvents:UIControlEventTouchUpInside];
    [_btnProtocol removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnProtocol addTarget:self action:@selector(btnProtocolAction:) forControlEvents:UIControlEventTouchUpInside];


    _textNickName.delegate  = self;
    _textPhoneNum.delegate  = self;

    _textPassWord.delegate  = self;

    _textAlingPasss.delegate  = self;
    self.textVerayCode.delegate = self;

 
    [_textNickName becomeFirstResponder];
    if (![self.string isEqualToString:@"2"]) {
        self.string = @"1";

    }


        [_btnVerification removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
        [_btnVerification addTarget:self action:@selector(btnVerification:) forControlEvents:UIControlEventTouchUpInside];


    [_textNickName becomeFirstResponder];

// Do any additional setup after loading the view from its nib.
}


-(void)btnVerification:(UIButton *)Verification
{



    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];


    [self.btnVerification setTitle:[NSString stringWithFormat:@"%@秒",[NSNumber numberWithInteger:countdownTiem60]] forState:UIControlStateNormal];

    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ActionRepeats:) userInfo:nil repeats:YES];

    BOOL isNum = [self VerifyMobileNumber:_textPhoneNum.text];



    if (!isNum) {

        UIAlertView * aler = [[UIAlertView alloc ] initWithTitle:@"提示" message:@"手机号码有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [aler show];
        return;
    }



    [self VerifyCodeRequest];

}

////检测是否是手机号码
//- (BOOL)VerifyMobileNumber:(NSString *)mobileNum
//{
//    /**
//     * 手机号码
//     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//     * 联通：130,131,132,152,155,156,185,186
//     * 电信：133,1349,153,180,189
//     * 虚拟：170
//     */
//    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9]|70)\\d{8}$";
//
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    if ([regextestmobile evaluateWithObject:mobileNum] == YES)
//    {
//        return YES;
//    }
//    else
//    {
//        return NO;
//    }
//}

-(void)ActionRepeats:(NSTimer *)timer
{

    countdownTiem60--;
    [self.btnVerification setTitle:[NSString stringWithFormat:@"%@秒",[NSNumber numberWithInteger:countdownTiem60]] forState:UIControlStateNormal];
    if (countdownTiem60==0) {
        [self.btnVerification setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];

        countdownTiem60 = 60;
        [timer invalidate];
    }


}

# pragma mark - network request 请求验证码

-(void)VerifyCodeRequest{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:10];
    //    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];


    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应



    NSString *   strUrl = [NSString stringWithFormat:@"%@%@", HostServerGetArea,CodeGetCodeAction];
    NSDictionary *dicJSON   = @{

                                @"phone":_textPhoneNum.text,

                                };

    //    NSError *error;
    //    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJSON options:NSJSONWritingPrettyPrinted error:&error];
    //    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //
    //    NSDictionary *param = nil;
    //
    //    param   = @{
    //                @"data":jsonString,
    //                };

    [manager POST:strUrl parameters:dicJSON success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [[LoadingView shareLoadingView] dismissAnimated:YES];

        NSDictionary * dicRespon  = responseObject;
        [self VerifyRequestWith:dicRespon];

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[LoadingView shareLoadingView] dismissAnimated:YES];
        [[NetWarningView sharedNetWarningView] show];  //警告网络异常
        NSLog(@"Error: %@", error);
        NSLog(@"请求出错了: - %@ %@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);


    }];



}

-(void)VerifyRequestWith:(NSDictionary *)dicRespon
{


    NSString * string  = [dicRespon objectForKey:@"success"];
    
    if (string.integerValue  == 1)
        
    {


        self.strCode = [[NSString alloc]  initWithFormat:@"%@",[dicRespon objectForKey:@"code"]];
        
        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:[dicRespon objectForKey:@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
    }


    else
    {

        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:[dicRespon objectForKey:@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
    }
}

//
//#pragma mark 添加通知
//-(void)viewWillAppear:(BOOL)animated{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification
//                                               object:nil];
//}
//
//#pragma mark 移除通知
//-(void)viewWillDisappear:(BOOL)animated{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}
//
//#pragma mark 键盘弹起
//- (void)keyboardWillShow:(NSNotification *)notif{
//
//    NSDictionary *userInfo = [notif userInfo];
//    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//
//    /* 获取键盘坐标 */
//    CGRect keyboardRect = [aValue CGRectValue];
//    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
//
//    /* 获取键盘Y轴坐标 */
//    NSInteger keyboard_Height = keyboardRect.size.height;
//
//    self.view.frame=self.view.frame=CGRectMake(0,0,winSize.width,winSize.height-TITLE_HEIGHT-keyboard_Height);
//}
//
//#pragma mark 键盘收起
//- (void)keyboardWillHide:(NSNotification *)notif{
//
//    self.view.frame=CGRectMake(0,0,winSize.width,winSize.height-TITLE_HEIGHT);
//}
//


-(void)btnBack:(UIButton *)back
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self selfViewAutomaticChangeLocationForView:textField];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width,self.view.frame.size.height);
    }];
    

}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    
    if (textField == _textNickName) {
        [_textPhoneNum becomeFirstResponder];
    }
    else if (textField == _textPhoneNum) {
        [_textPassWord becomeFirstResponder];
    }
    else if (textField == _textPassWord) {
        [_textAlingPasss becomeFirstResponder];
    }
    
    [textField resignFirstResponder];
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width,self.view.frame.size.height);
    }];
    [[[UIApplication sharedApplication].delegate window] endEditing:YES];


    return YES;
}

-(void)btnProtocolAction:(UIButton * )sender
{
    ProtocoliewWebController *  ProtocoliewWe = [[ProtocoliewWebController alloc] initWithNibName:@"ProtocoliewWebController" bundle:nil];
    [self presentViewController:ProtocoliewWe animated:YES completion:^{
        
    }];

}

-(void)btnImmediatelyRegister:(UIButton * )sender
{
    
    [[[UIApplication sharedApplication] keyWindow]endEditing:YES];
    
    BOOL mobileNum = [self VerifyMobileNumber:_textPhoneNum.text];
    //    BOOL VerifyNameWith = [self VerifyNameWith:_textAccount.text];
    //    if (_textAccount.text.length == 0 && VerifyNameWith == NO)
    //        {
    //        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"您的账号格式有误" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    //        [alter show];
    //        return ;
    //        }
    //    else
    if (_textNickName.text.length >5)
    {
        
        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"昵称字数超限" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alter show];
        return ;
        
        
        
    }
    else if (_textPassWord.text.length <6)
    {
        
        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"密码不能小于6位" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alter show];
        return ;
        
        
        
    }
    else if (mobileNum == NO)
        
    {
        
        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"您的手机号码有误" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alter show];
        return ;
        
    }
    else if (![_textPassWord.text isEqualToString:_textAlingPasss.text])
        
    {
        
        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"两次密码不一致" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alter show];
        return ;
        
    }
    else if (![self.strCode isEqualToString:self.textVerayCode.text])

    {

        UIAlertView * alter  = [[UIAlertView alloc] initWithTitle:@"比输入的验证码不对，请重新输入" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alter show];
        return ;
    }
    



    [self RequestRec];
    
    
}

//检测是否是手机号码
- (BOOL)VerifyMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     * 虚拟：170
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9]|70)\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
    
}
//用户名筛选
- (BOOL)VerifyNameWith:(NSString *)userName
{
    //以字母开头，只能由数字与字母组成
    NSString * namePre = @"^[a-zA-Z][a-zA-Z0-9]{3,15}$";
    
    NSPredicate *regextestName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", namePre];
    if ([regextestName evaluateWithObject:namePre] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma mark - network request

-(void)RequestRec
{
    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,register_commit];
    
    
    NSString * strPaw = [Common md5_32:_textPassWord.text];
    
    NSDictionary *params = @{
                             

                                 @"userName":[NSString stringWithFormat:@"%@",_textNickName.text],
                                 @"phone":[NSString stringWithFormat:@"%@",_textPhoneNum.text],
                                 @"password":strPaw,
                                 @"type":self.string
                             };
    

    
    
    
    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         

//               NSData *doubi = responseObject   ;
//                   //     JSON格式的NSString转换成NSMutableDictionary
//               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
//         
//               NSError *err = nil;
//               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
     
         NSDictionary * dicRespon = responseObject;
         [self RequestSuccessWith:dicRespon];
         
         
         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
//              NSData *doubi = operation.error    ;
//                  //     JSON格式的NSString转换成NSMutableDictionary
//              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
//         
//              NSError *err = nil;
//              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];
    
}

-(void)RequestSuccessWith:(NSDictionary *)dicRespon
{
    
    NSString * code = [dicRespon objectForKey:@"success"];
    if ([code isEqualToString:@"true"])
    {
//        NSDictionary *dicTmp  = [dicRespon objectForKey:@"message"] ;
//        
        ShareUserModel * shareUser = [ShareUserModel shareUserModel];
    
        [shareUser.user setSessionId:[dicRespon objectForKey:@"sessionId"] ];
    
    
    
    [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
    
    

    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];

    
      
        
    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[ dicRespon  objectForKey:@"message"]];

    }
    
}



//键盘挡住
-(void)selfViewAutomaticChangeLocationForView:(UITextField *)textView{
    
    UITextPosition * pos=[textView.selectedTextRange valueForKey:@"start"];
    NSInteger hight = 216;
    CGRect cursorRect = [textView caretRectForPosition:pos];
    
    CGRect rect = [self.view convertRect:cursorRect fromView:textView];
    if (CGRectGetMaxY(rect)>(self.view.frame.size.height-hight*2/2)) {
        [UIView animateWithDuration:0.2 animations:^{
            self.view.frame = CGRectMake(self.view.frame.origin.x, -(CGRectGetMaxY(rect)-(self.view.frame.size.height-hight*2)), self.view.frame.size.width, self.view.frame.size.height);
        }];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
